package com.btl.cygf;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import com.btl.bean.ZuiXin;
import com.btl.sqlite.DbOpService;
import com.btl.sqlite.History;
import com.btl.utils.DownTuUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SouSuoResult extends Activity implements OnClickListener {

	private PullToRefreshListView mListView;
	private LinkedList<ZuiXin> listItems = new LinkedList<ZuiXin>(); // 数据源集合
	private ArrayAdapter<String> mAdapter;
	private MyListAdapter myListAdapter;
	private AsyncHttpClient client;
	private RequestParams params;
	private int v_id;
	private int lastid;
	private String condition;

	ImageView login_backtofragment;
	TextView title;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_fenlei);

		login_backtofragment = (ImageView) findViewById(R.id.login_backtofragment);
		login_backtofragment.setOnClickListener(this);
		title = (TextView) findViewById(R.id.fenlei_title_txt);
		title.setText("搜索结果");

		condition = getIntent().getStringExtra("condition");

		/**
		 * 异步加载网络资源信息
		 */
		client = new AsyncHttpClient();
		// 像网络传输的数据
		params = new RequestParams();
		Log.i("sort", "456");
		// 链接到网络，获取数据
		getDataRefresh();

		mListView = (PullToRefreshListView) findViewById(R.id.list_zuixin);

		mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// Do work to refresh the list here.
				if (mListView.isHeaderShown()) {
					// 下拉刷新
					getDataRefresh();
				} else if (mListView.isFooterShown()) {
					// 上拉加载
					getDataMore(v_id);
				}
			}
		});

		mListView.setMode(Mode.BOTH);
		mListView.getLoadingLayoutProxy(false, true).setPullLabel("加载完成");
		mListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载");
		mListView.getLoadingLayoutProxy(false, true).setReleaseLabel("上拉以加载");
		mListView.getRefreshableView().setAdapter(mAdapter);

		// listItems = getListItems();
		myListAdapter = new MyListAdapter();
		mListView.setAdapter(myListAdapter);

	}

	// 点击返回
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_backtofragment:
			this.finish();
			break;

		}
	}

	/**
	 * 连接到网络 获取数据
	 * 
	 * @param pagenow
	 */
	private void getDataRefresh() {
		params.remove("condition");
		params.add("condition", condition);
		// 实例LinkList数据源
		listItems = new LinkedList<ZuiXin>();
		// 连接查看分类（刷新）
		client.post(getResources().getString(R.string.url)
				+ "/CYGF/sendRefreshJason.search", params,
				new JsonHttpResponseHandler() {
					// 链接成功做出的反应
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONArray response) {
						JSONObject object1 = response.optJSONObject(1);
						for (int i = 0; i < response.length(); i++) {
							ZuiXin zuiXin = new ZuiXin();
							JSONObject object = response.optJSONObject(i);
							String s1 = object.optString("v_image");
							String s2 = object.optString("v_title");
							int s3 = object.optInt("v_shoucang");
							int s4 = object.optInt("v_dianzan");
							String s5 = object.optString("v_cailiao");
							int s6 = object.optInt("v_id");
							String s7 = object.optString("v_intro");
							zuiXin.setVid(s6);
							zuiXin.setPicture(s1);
							zuiXin.setTitle(s2);
							zuiXin.setShoucang(s3);
							zuiXin.setDianzan(s4);
							zuiXin.setCailiao(s5);
							zuiXin.setInfo(s7);
							lastid = object.optInt("lastid");
							listItems.add(zuiXin);
							// listItems.addFirst(zuiXin);
							zuiXin = null;
							if (i == (response.length() - 1)) {
								v_id = object.optInt("v_id");
							}
						}
						// BaseAdapter数据发生改变
						myListAdapter.notifyDataSetChanged();
						mListView.onRefreshComplete();
						super.onSuccess(statusCode, headers, response);
					}

					// 链接网络失败，做出的反应
					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONArray errorResponse) {
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
	}

	/**
	 * 下拉加载更多
	 */
	private void getDataMore(final int vid) {
		params.remove("v_id");
		params.add("v_id", vid + "");
		// 连接查看分类（加载）
		client.post(getResources().getString(R.string.url)
				+ "/CYGF/sendMoreJason.search", params,
				new JsonHttpResponseHandler() {
					// 链接成功做出的反应
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONArray response) {
						Log.i("vid", vid + "");
						Log.i("vid", lastid + "");
						if (vid == lastid) {
							mListView.getLoadingLayoutProxy(false, true)
									.setRefreshingLabel("没有更多选项");
							// mListView.setMode(Mode.DISABLED);
							new GetDataTask().execute();
						} else {
							for (int i = 0; i < response.length(); i++) {
								ZuiXin zuiXin = new ZuiXin();
								JSONObject object = response.optJSONObject(i);
								String s1 = object.optString("v_image");
								String s2 = object.optString("v_title");
								int s3 = object.optInt("v_shoucang");
								int s4 = object.optInt("v_dianzan");
								String s5 = object.optString("v_cailiao");
								String s7 = object.optString("v_intro");
								int s6 = object.optInt("v_id");
								zuiXin.setInfo(s7);
								zuiXin.setVid(s6);
								zuiXin.setPicture(s1);
								zuiXin.setTitle(s2);
								zuiXin.setShoucang(s3);
								zuiXin.setDianzan(s4);
								zuiXin.setCailiao(s5);
								listItems.add(zuiXin);
								// listItems.addFirst(zuiXin);
								zuiXin = null;
								if (i == (response.length() - 1)) {
									v_id = object.optInt("v_id");
								}
							}
							// BaseAdapter数据发生改变
							myListAdapter.notifyDataSetChanged();
							mListView.onRefreshComplete();

						}

						super.onSuccess(statusCode, headers, response);
					}

					// 链接网络失败，做出的反应
					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONArray errorResponse) {
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
	}

	/**
	 * listview的适配器MyListAdapter
	 */
	private class MyListAdapter extends BaseAdapter {

		class ListItemView {
			public ImageView image;
			public TextView title;
			public TextView shoucang;
			public TextView zan;
			public TextView cailiao;
		}

		@Override
		public int getCount() {
			return listItems.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return listItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// listItems.get(position-1).getVid();-------->当前选中条目的id

					SharedPreferences share = getApplicationContext()
							.getSharedPreferences("login",
									Activity.MODE_WORLD_READABLE);
					String username = share.getString("id", "");
					if (!username.equals("")) {
						SimpleDateFormat myFmt = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						Date now = new Date();
						History history = new History();
						history.setUsername(username);
						history.setVid(listItems.get(position - 1).getVid()
								+ "");
						history.setTitle(listItems.get(position - 1).getTitle());
						history.setIntro(listItems.get(position - 1).getInfo());
						history.setVtime(myFmt.format(now));
						DbOpService db = new DbOpService(
								getApplicationContext());
						db.Insert(history);
					}
					Intent intent = new Intent();
					intent.setClass(SouSuoResult.this, TieZiActivity.class);
					intent.putExtra("v_id", listItems.get(position - 1)
							.getVid() + "");
					Log.i("v_id", listItems.get(position - 1).getVid() + "");
					startActivity(intent);
				}
			});

			// final int selectID = position;
			// 自定义视图
			ListItemView listItemView = null;
			if (convertView == null) {
				listItemView = new ListItemView();
				// 获取list_item布局文件的视图
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.fenlei_item_list, null);
				// 获取控件对象
				listItemView.image = (ImageView) convertView
						.findViewById(R.id.img);
				listItemView.title = (TextView) convertView
						.findViewById(R.id.title);
				listItemView.shoucang = (TextView) convertView
						.findViewById(R.id.shoucang_fenlei);
				listItemView.zan = (TextView) convertView
						.findViewById(R.id.zan_fenglei);
				listItemView.cailiao = (TextView) convertView
						.findViewById(R.id.cailiao);
				// 设置控件集到convertView
				convertView.setTag(listItemView);
			} else {
				listItemView = (ListItemView) convertView.getTag();
			}

			// 设置文字和图片
			ImageLoader imageLoader = ImageLoader.getInstance();

			imageLoader.init(DownTuUtils.getConfig(SouSuoResult.this));

			imageLoader.displayImage(listItems.get(position).getPicture(),
					listItemView.image, DownTuUtils.getOptions());
			// listItemView.image.setImageBitmap(new
			// BitmapFactory().decodeByteArray(data, offset, length))
			listItemView.title.setText(listItems.get(position).getTitle());
			listItemView.shoucang.setText(listItems.get(position).getShoucang()
					+ "");
			listItemView.zan.setText(listItems.get(position).getDianzan() + "");
			listItemView.cailiao.setText(listItems.get(position).getCailiao()
					+ "");
			return convertView;
		}

	}

	private class GetDataTask extends AsyncTask<Void, Void, String> {

		// 后台处理部分
		@Override
		protected String doInBackground(Void... params) {
			// Simulates a background job.
			// mListView.getLoadingLayoutProxy(false,
			// true).setRefreshingLabel("没有更多选项");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
			}
			String str = "Added after refresh...I add";
			return str;
		}

		// 这里是对刷新的响应，可以利用addFirst（）和addLast()函数将新加的内容加到LISTView中
		// 根据AsyncTask的原理，onPostExecute里的result的值就是doInBackground()的返回值
		@Override
		protected void onPostExecute(String result) {

			// 通知程序数据集已经改变，如果不做通知，那么将不会刷新mListItems的集合
			// myListAdapter.notifyDataSetChanged();
			// 32tCall onRefreshComplete when the list has been refreshed.
			mListView.onRefreshComplete();
			super.onPostExecute(result);
		}
	}

}
